<template>
   <div class="app-container">
      <el-form :model="conditionForm" ref="queryRef" :inline="true" size="small" v-show="showSearch">
         <!-- <el-form-item label="字典名称" prop="dictType">
            <el-select v-model="conditionForm.dictType" style="width: 200px">
               <el-option v-for="item in typeOptions" :key="item.dictId" :label="item.dictName" :value="item.dictType" />
            </el-select>
         </el-form-item> -->
         <el-form-item label="字典标签" prop="dictLabel">
            <el-input v-model="conditionForm.dictLabel" placeholder="请输入字典标签" clearable style="width: 240px"
               @keyup.enter="setCondition" />
         </el-form-item>
         <el-form-item label="状态" prop="flags">
            <el-select v-model="conditionForm.flags" placeholder="数据状态" clearable style="width: 240px">
               <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
         </el-form-item>
         <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="setCondition">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
         </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
         <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" @click="handleAdd"
               v-hasPermi="['system:dict:add']">新增</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button type="success" plain icon="el-icon-edit" :disabled="single" @click="handleUpdate"
               v-hasPermi="['system:dict:edit']">修改</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button type="danger" plain icon="el-icon-delete" :disabled="multiple" @click="handleDelete"
               v-hasPermi="['system:dict:remove']">删除</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button type="warning" plain icon="el-icon-close" @click="handleClose">关闭</el-button>
         </el-col>
         <right-toolbar :showSearch="showSearch" @updateShowSearch="updateShowSearch"
            @queryTable="selectData"></right-toolbar>
      </el-row>

      <el-table v-loading="tableLoading" :data="dataTable" @selection-change="handleSelectionChange">
         <el-table-column type="selection" width="55" align="center" />
         <!-- <el-table-column label="字典编码" align="center" prop="businessId" /> -->
         <el-table-column label="字典标签" align="left" prop="dictLabel">
            <template #default="scope">
               <span
                  v-if="(scope.row.listClass == '' || scope.row.listClass == 'default') && (scope.row.cssClass == '' || scope.row.cssClass == null)">{{
                     scope.row.dictLabel }}</span>
               <!-- <el-tag v-else :type="scope.row.listClass == 'primary' ? '' : scope.row.listClass"
                  :class="scope.row.cssClass">{{ scope.row.dictLabel }}</el-tag> -->
               <el-tag v-else :type="scope.row.listClass ? scope.row.listClass : 'primary'" :class="scope.row.cssClass"
                  effect="light" style="width: 100%;">{{
                     scope.row.dictLabel }}</el-tag>
            </template>
         </el-table-column>
         <el-table-column label="字典键值" align="center" prop="dictKey" width="90" />
         <el-table-column label="字典排序" align="center" prop="dictSort" width="60" />
         <el-table-column label="状态" align="center" prop="flags">
            <template #default="scope">
               <dict-tag :options="sys_normal_disable" :value="scope.row.flags" />
            </template>
         </el-table-column>
         <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
         <el-table-column label="创建时间" align="center" prop="createTime" width="180">
            <template #default="scope">
               <span>{{ timeFormat(scope.row.createTime, 'y2s') }}</span>
            </template>
         </el-table-column>
         <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
            <template #default="scope">
               <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                  v-hasPermi="['system:dict:edit']">修改</el-button>
               <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                  v-hasPermi="['system:dict:remove']">删除</el-button>
            </template>
         </el-table-column>
      </el-table>

      <el-pagination :total="pageInfo.total" background layout="total,sizes, prev, pager, next"
         :page-size="pageInfo.pageSize" :current-page="pageInfo.pageIndex" :page-sizes="[10, 20, 30, 40, 50]"
         @size-change="pageSizeChange" @current-change="selectData" style="float:right;"></el-pagination>

      <!-- 添加或修改参数配置对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="500px" :close-on-click-modal="false"
         :close-on-press-escape="false" append-to-body>
         <el-form ref="dataRef" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="字典类型">
               <el-input v-model="form.dictType" :disabled="true" />
            </el-form-item>
            <el-form-item label="数据标签" prop="dictLabel">
               <el-input v-model="form.dictLabel" placeholder="请输入数据标签" />
            </el-form-item>
            <el-form-item label="数据键值" prop="dictKey">
               <el-input v-model="form.dictKey" placeholder="请输入数据键值" />
            </el-form-item>
            <!-- <el-form-item label="样式属性" prop="cssClass">
               <el-input v-model="form.cssClass" placeholder="请输入样式属性" />
            </el-form-item> -->
            <el-form-item label="显示排序" prop="dictSort">
               <el-input-number v-model="form.dictSort" controls-position="right" :min="0" />
            </el-form-item>
            <!-- <el-form-item label="回显样式" prop="listClass">
               <el-select v-model="form.listClass">
                  <el-option v-for="item in listClassOptions" :key="item.value"
                     :label="item.label + '(' + item.value + ')'" :value="item.value"></el-option>
               </el-select>
            </el-form-item> -->
            <el-form-item label="状态" prop="flags">
               <el-radio-group v-model="form.flags">
                  <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.value">{{ dict.label
                  }}</el-radio>
               </el-radio-group>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
               <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitForm">确 定</el-button>
               <el-button @click="cancel">取 消</el-button>
            </div>
         </template>
      </el-dialog>
   </div>
</template>

<script lang="ts" setup name="Data">
import useDictStore from '@/stores/dict'
import { getType, listData, getData, delData, addData, updateData } from "@/requests/api/dict";
import { ref, reactive, toRefs, Ref } from "vue";
import { useRoute, useRouter } from 'vue-router/composables';
import { conditionDictItemCommon, dictItemInit, dictTypeInit } from './data';
import { useReset } from '@/hooks/useReset';
import { Message, MessageBox } from 'element-ui';
import { timeFormat, timeRangeTransform } from "@/utils/time";
import DictTag from '@/components/DictTag.vue';
import RightToolbar from '@/components/RightToolbar.vue';
import { useShowSearch } from '@/hooks/useShowSearch';
import { queryParamsInit } from '@/views/data';
import { usePagination } from '@/hooks/usePagination';

const { showSearch, updateShowSearch } = useShowSearch();
// const { proxy } = getCurrentInstance();
const sys_normal_disable = ref(dictTypeInit)
const open = ref(false);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const title = ref("");
const defaultDictType = ref("");
const route = useRoute();
const router = useRouter();

const data = reactive({
   form: Object.assign({}, dictItemInit),
   conditionForm: Object.assign({
      dateTimes: [],
   }, conditionDictItemCommon),
   queryParams: Object.assign({
      condition: Object.assign({
         "startTime": "",
         "endTime": ""
      }, conditionDictItemCommon)
   }, queryParamsInit),
   rules: {
      dictLabel: [{ required: true, message: "数据标签不能为空", trigger: "blur" }],
      dictKey: [{ required: true, message: "数据键值不能为空", trigger: "blur" }],
      dictSort: [{ required: true, message: "数据顺序不能为空", trigger: "blur" }]
   }
});

const { conditionForm, queryParams, form, rules } = toRefs(data);
/** 查询字典数据列表 */
const { dataTable,
   pageInfo,
   pageSizeChange,
   selectData, tableLoading } = usePagination(queryParams, listData)

/** 查询字典类型详细 */
const getTypes = async (dictId: string) => {
   const res = await getType(dictId)
   if (res && res.data) {
      queryParams.value.condition.dictType = res.data.dictType;
      defaultDictType.value = res.data.dictType;
      selectData();
   }

}


/** 取消按钮 */
const cancel = () => {
   open.value = false;
   reset();
}
/** 搜索按钮操作 */
const setCondition = () => {
   console.log('查询条件', conditionForm.value)
   pageInfo.value.pageIndex = 1; // 最好重置pageIndex，因为有些数据很少，当处于非首页查询时容易误解
   if (queryParams.value.condition) {
      const { dateTimes, dictLabel, flags } = conditionForm.value // dictType是固定的
      queryParams.value.condition.flags = flags;
      queryParams.value.condition.dictLabel = dictLabel;
      timeRangeTransform(dateTimes, queryParams);
   }
   selectData();
}
/** 重置按钮操作 */
const queryRef: Ref<any> = ref(null)
/** 表单重置 */
const dataRef: Ref<any> = ref(null)
const { reset, resetQuery } = useReset({
   form,
   formInit: Object.assign({}, dictItemInit),
   formRef: dataRef,
   conditionForm: queryParams,
   conditionFormRef: queryRef,
   request: setCondition,
   other: defaultDictType.value
})


/** 返回按钮操作 */
const handleClose = () => {
   const obj = { path: "/sysAdmin/dictSetting" };
   router.push(obj)
   // proxy.$tab.closeOpenPage(obj);
   // todo 上面是tab标签页的关闭，打开新的页面
}

/** 新增按钮操作 */
const handleAdd = () => {
   reset();
   open.value = true;
   title.value = "添加字典数据";
   form.value.dictType = queryParams.value.condition.dictType;
}
/** 多选框选中数据 */
const handleSelectionChange = (selection: any) => {
   ids.value = selection.map((item: any) => item.businessId);
   single.value = selection.length != 1;
   multiple.value = !selection.length;
}
/** 修改按钮操作 */
const handleUpdate = async (row: any) => {
   reset();
   const businessId = row.businessId || ids.value;
   const res = await getData(businessId)
   if (res.data) {
      open.value = true;
      form.value = res.data;
      title.value = "修改字典数据";
   } else {
      Message.error("数据获取失败");
   }

}
/** 提交按钮 */
const submitForm = () => {
   dataRef.value.validate((valid: any) => {
      if (valid) {
         if (form.value.businessId != undefined) {
            updateData(form.value).then(() => {
               useDictStore().removeDict(queryParams.value.condition.dictType);
               Message.success("修改成功");
               open.value = false;
               selectData();
            });
         } else {
            addData(form.value).then(() => {
               useDictStore().removeDict(queryParams.value.condition.dictType);
               Message.success("新增成功");
               open.value = false;
               selectData();
            });
         }
      }
   });
}
/** 删除按钮操作 */
const handleDelete = (row: any) => {
   const businessIds = row.businessId || ids.value;
   MessageBox.confirm('是否确认删除字典编码为"' + businessIds + '"的数据项？').then(() => {
      return delData(businessIds);
   }).then(() => {
      selectData();
      Message.success("删除成功");
      useDictStore().removeDict(queryParams.value.condition.dictType);
   }).catch(() => { });
}
getTypes(route.params && route.params.dictId);
</script>
<style lang="scss" scoped>
:deep(.el-tag) {
   display: inline-block; // 内联块级元素
   white-space: pre-wrap; // 保留空白字符并允许文本自动换行
   word-wrap: break-word; // 单词太长允许在单词内部进行换行
}
</style>
